import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import FileSystemModel
import SystemIconProvider

Rectangle {
    id: noticePanel
    color: "#f5f5f5"
    border.color: "#d0d0d0"
    border.width: 1
    
    // 窗口工具栏
    WindowToolBar {
        id: windowToolBar
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        mainWindow: ApplicationWindow.window
        title: "消息中心"
    }
    
    ColumnLayout {
        anchors.top: windowToolBar.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.margins: 0
        spacing: 0
        
        // 筛选标签栏
        Rectangle {
            id: filterBar
            Layout.fillWidth: true
            height: 50
            color: "#ffffff"
            border.color: "#eeeeee"
            border.width: 1
            
            RowLayout {
                anchors.fill: parent
                anchors.margins: 15
                spacing: 0
                
                // 未读标签
                Rectangle {
                    id: unreadTab
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: currentTab === 0 ? "#007AFF" : "transparent"
                    radius: 5
                    
                    RowLayout {
                        anchors.centerIn: parent
                        spacing: 8
                        
                        Text {
                            text: "未读"
                            font.pixelSize: 16
                            color: currentTab === 0 ? "#ffffff" : "#666666"
                            font.bold: currentTab === 0
                        }
                        
                        Rectangle {
                            id: unreadBadge
                            width: unreadCount > 0 ? Math.max(20, unreadCountText.width + 12) : 0
                            height: unreadCount > 0 ? 20 : 0
                            radius: 10
                            color: currentTab === 0 ? "#ffffff" : "#ff6b6b"
                            visible: unreadCount > 0
                            
                            Text {
                                id: unreadCountText
                                anchors.centerIn: parent
                                text: unreadCount.toString()
                                font.pixelSize: 12
                                color: currentTab === 0 ? "#007AFF" : "#ffffff"
                                font.bold: true
                            }
                        }
                    }
                    
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            currentTab = 0
                            resetData()
                            getNoticesData()
                        }
                    }
                }
                
                // 全部标签
                Rectangle {
                    id: allTab
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: currentTab === -1 ? "#007AFF" : "transparent"
                    radius: 5
                    
                    RowLayout {
                        anchors.centerIn: parent
                        spacing: 8
                        
                        Text {
                            text: "全部"
                            font.pixelSize: 16
                            color: currentTab === -1 ? "#ffffff" : "#666666"
                            font.bold: currentTab === -1
                        }
                        
                        Rectangle {
                            id: totalBadge
                            width: totalCount > 0 ? Math.max(20, totalCountText.width + 12) : 0
                            height: totalCount > 0 ? 20 : 0
                            radius: 10
                            color: currentTab === -1 ? "#ffffff" : "#ff6b6b"
                            visible: totalCount > 0
                            
                            Text {
                                id: totalCountText
                                anchors.centerIn: parent
                                text: totalCount.toString()
                                font.pixelSize: 12
                                color: currentTab === -1 ? "#007AFF" : "#ffffff"
                                font.bold: true
                            }
                        }
                    }
                    
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            currentTab = -1
                            resetData()
                            getNoticesData()
                        }
                    }
                }
            }
        }
        
        // 通知列表区域
        ScrollView {
            id: scrollView
            Layout.fillWidth: true
            Layout.fillHeight: true
            clip: true
            Layout.margins: 10
            
            ListView {
                id: noticesList
                model: noticesModel
                spacing: 8 // 增加列表项之间的间距
                
                delegate: Rectangle {
                    id: noticeItem
                    width: noticesList.width
                    height: Math.max(120, noticeContent.implicitHeight + 80) // 确保最小高度
                    color: "#ffffff"
                    border.color: "#eeeeee"
                    border.width: 1
                    
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            console.log("点击通知:", model.id, "标题:", model.summary)
                            handleNoticeClick(model)
                        }
                    }
                    
                    ColumnLayout {
                        anchors.fill: parent
                        anchors.margins: 16
                        spacing: 8
                        
                        // 通知头部
                        RowLayout {
                            Layout.fillWidth: true
                            spacing: 12
                            
                            // 通知标题                            
                            // 已读状态
                            Rectangle {
                                width: 40
                                height: 20
                                radius: 10
                                color: model.read ? "#999999" : "#ff6b6b"
                                
                                Text {
                                    anchors.centerIn: parent
                                    text: model.read ? "已读" : "未读"
                                    font.pixelSize: 12
                                    color: "#ffffff"
                                }
                            }
                        }
                        
                        // 通知内容
                        Text {
                            id: noticeContent
                            Layout.fillWidth: true
                            text: parseContent(model.content || "")
                            textFormat: Text.RichText
                            font.pixelSize: 14
                            color: "#666666"
                            wrapMode: Text.WordWrap
                            maximumLineCount: 2
                            elide: Text.ElideRight
                        }
                        
                        // 通知底部信息
                        RowLayout {
                            Layout.fillWidth: true
                            spacing: 16
                            
                            Text {
                                text: model.createTime || ""
                                font.pixelSize: 12
                                color: "#999999"
                            }
                            
                            Item {
                                Layout.fillWidth: true
                            }
                            
                            Text {
                                text: model.module || ""
                                font.pixelSize: 12
                                color: "#666666"
                            }
                        }
                    }
                }
            }
        }
        
        // 加载状态指示器
        Rectangle {
            id: loadingIndicator
            Layout.fillWidth: true
            height: 40
            color: "#f5f5f5"
            visible: isLoading
            
            BusyIndicator {
                anchors.centerIn: parent
                running: isLoading
            }
            
            Text {
                anchors.centerIn: parent
                text: "正在加载..."
                font.pixelSize: 14
                color: "#666666"
                visible: isLoading
            }
        }
        
        // 空状态提示
        Rectangle {
            id: emptyState
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "#f5f5f5"
            visible: noticesModel.count === 0 && !isLoading && errorMessage === ""
            
            ColumnLayout {
                anchors.centerIn: parent
                spacing: 16
                
                Text {
                    text: "暂无消息"
                    font.pixelSize: 16
                    color: "#999999"
                    Layout.alignment: Qt.AlignHCenter
                }
            }
        }
        
        // 错误信息显示
        Rectangle {
            id: errorState
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "#f5f5f5"
            visible: errorMessage !== ""
            
            ColumnLayout {
                anchors.centerIn: parent
                spacing: 16
                
                Text {
                    text: errorMessage
                    font.pixelSize: 14
                    color: "#ff4444"
                    Layout.alignment: Qt.AlignHCenter
                    wrapMode: Text.WordWrap
                }
                
                Button {
                    text: "重试"
                    Layout.alignment: Qt.AlignHCenter
                    onClicked: {
                        errorMessage = ""
                        getNoticesData()
                    }
                }
            }
        }
    }
    
    // 通知数据模型
    ListModel {
        id: noticesModel
    }
    
    // 状态变量
    property int currentTab: 0  // 0: 未读, -1: 全部
    property bool isLoading: false
    property string errorMessage: ""
    property int unreadCount: 0
    property int totalCount: 0
    property int currentPage: 1
    property bool finished: false
    
    // 组件加载时获取通知列表
    Component.onCompleted: {
        getNoticesData()
    }
    
    // 获取通知列表数据
    function getNoticesData() {
        console.log("开始获取通知列表，当前标签:", currentTab, "页码:", currentPage)
        
        if (isLoading) {
            console.log("正在加载中，跳过重复请求")
            return
        }
        
        isLoading = true
        errorMessage = ""
        
        // 通过 CommandExecutor 获取通知列表
        // 将 -1 转换为 -1 传递给 API（-1 表示不筛选读取状态）
        // 0 表示未读，1 表示已读，-1 表示全部
        var readStatus = currentTab === -1 ? -1 : currentTab
        commandExecutor.executeGetNotice(readStatus, 0, currentPage, 30) // 默认每页30条
    }
    
    // 重置数据
    function resetData() {
        console.log("重置通知数据")
        currentPage = 1
        finished = false
        noticesModel.clear()
        unreadCount = 0
        totalCount = 0
        errorMessage = ""
    }
    
    // 解析通知内容
    function parseContent(content) {
        if (!content) return ""
        
        try {
            // 尝试解析JSON格式的内容
            var parsed = JSON.parse(content)
            var text = parsed.content || content
            
            // 清理HTML标签和特殊字符
            text = text.replace(/<[^>]*>/g, '') // 移除HTML标签
            text = text.replace(/&nbsp;/g, ' ') // 替换HTML空格
            text = text.replace(/&amp;/g, '&') // 替换HTML实体
            text = text.replace(/&lt;/g, '<')
            text = text.replace(/&gt;/g, '>')
            text = text.replace(/&quot;/g, '"')
            text = text.replace(/\\n/g, '\n') // 处理换行符
            text = text.replace(/\n+/g, ' ') // 将多个换行符合并为单个空格
            text = text.trim() // 去除首尾空格
            
            return text
        } catch (e) {
            // 如果不是JSON格式，直接清理HTML标签
            var text = content
            text = text.replace(/<[^>]*>/g, '') // 移除HTML标签
            text = text.replace(/&nbsp;/g, ' ') // 替换HTML空格
            text = text.replace(/&amp;/g, '&') // 替换HTML实体
            text = text.replace(/&lt;/g, '<')
            text = text.replace(/&gt;/g, '>')
            text = text.replace(/&quot;/g, '"')
            text = text.replace(/\\n/g, '\n') // 处理换行符
            text = text.replace(/\n+/g, ' ') // 将多个换行符合并为单个空格
            text = text.trim() // 去除首尾空格
            
            return text
        }
    }
    
    // 处理通知点击事件
    function handleNoticeClick(notice) {
        console.log("处理通知点击事件:", notice)
        
        if (!notice.read) {
            // 标记为已读 - 通过 CommandExecutor 执行
            commandExecutor.executeMarkReadNotice(notice.id)
            
            // 更新未读数量
            unreadCount = Math.max(0, unreadCount - 1)
            
            // 更新模型中的状态
            for (var i = 0; i < noticesModel.count; i++) {
                if (noticesModel.get(i).id === notice.id) {
                    noticesModel.setProperty(i, "read", true)
                    break
                }
            }
        }
        
        // 这里可以添加跳转到具体页面的逻辑
        // 例如：mainStackView.push("qrc:/pages/NoticeDetail.qml", {notice: notice})
        var accessToken = backendService.getAccessToken();
        var serverHost = backendService.loadServerHost();
        if (serverHost === "") {
            serverHost = "http://localhost:8888";
        }
        // var url = serverHost + "/signon/api/open-app?accessToken=" + accessToken + "&appId=" + notice.module;

        console.log("notice.linkParams", notice.linkParams);
        
        // 解析 linkParams JSON 字符串
        var docid = notice.id;  // 默认值
        var formid = "";  // 默认值
        var appid = notice.module;  // 默认值
        
        if (notice.linkParams && notice.linkParams !== "") {
            try {
                var linkParamsObj = JSON.parse(notice.linkParams);
                console.log("解析后的 linkParams:", linkParamsObj);
                
                // 获取 docid（对应 _docid）
                if (linkParamsObj._docid) {
                    docid = linkParamsObj._docid;
                }
                
                // 获取 formid（对应 _formid）
                if (linkParamsObj._formid) {
                    formid = linkParamsObj._formid;
                }
                
                // 获取 appid（对应 application）
                if (linkParamsObj.application) {
                    appid = linkParamsObj.application;
                }
                
                console.log("提取的值 - docid:", docid, "formid:", formid, "appid:", appid);
            } catch (e) {
                console.log("解析 linkParams 失败:", e);
            }
        }
        
        var url = serverHost + "/static/portal/vue/index.html#/open?appId="+appid+"&docid="+docid+"&actionContent="+formid+"&opentarget=detail&linkType=00&accessToken=" + accessToken;
        Qt.openUrlExternally(url);
        console.log("通知点击处理完成")
    }
    
    // 连接 CommandExecutor 信号
    Connections {
        target: commandExecutor
        
        function onGetNoticeCompleted(resultCode, message, notices) {
            console.log("获取通知列表完成:", resultCode, message, notices.length)
            isLoading = false
            
            if (resultCode === 0) {
                if (currentPage === 1) {
                    // 第一页，清空现有数据
                    noticesModel.clear()
                }
                
                // 添加新数据
                for (var i = 0; i < notices.length; i++) {
                    var notice = notices[i]
                    noticesModel.append({
                        id: notice.id || "",
                        summary: notice.summary || "",
                        content: notice.content || "",
                        createTime: notice.createTime || "",
                        module: notice.module || "",
                        read: notice.read || false,
                        linkParams: notice.linkParams || ""
                    })
                }
                
                // 更新计数
                if (currentPage === 1) {
                    totalCount = notices.length
                    if (currentTab === 0) {
                        unreadCount = notices.length
                    }
                }
                
                // 判断是否加载完毕
                if (notices.length < 10) {
                    finished = true
                } else {
                    currentPage++
                }
                
                console.log("通知列表更新完成，共", noticesModel.count, "条通知")
            } else {
                errorMessage = "获取通知列表失败: " + message
                console.log("获取通知列表失败:", message)
            }
        }
        
        function onMarkReadNoticeCompleted(resultCode, message, noticeId) {
            console.log("标记已读通知完成:", resultCode, message, noticeId)
            if (resultCode === 0) {
                console.log("通知标记为已读成功:", noticeId)
            } else {
                console.log("通知标记为已读失败:", message)
                // 如果标记失败，可以在这里处理错误，比如恢复未读状态
            }
        }
        
        function onNetworkError(errorCode, errorString) {
            console.log("网络错误:", errorCode, errorString)
            isLoading = false
            errorMessage = "网络错误: " + errorString
        }
    }
}